﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Windows.Controls;
using MessageBox = System.Windows.MessageBox;

namespace ImmovablesManager
{
    /// <summary>
    /// Interaction logic for PlotCard.xaml
    /// </summary>
    public partial class PlotCard : Window
    {

        private Guid _realtorId;
        private bool _isEdit;
        private Guid _plotId;
        private string _numberCard;
        private Guid _plotNewGuid;

        public PlotCard()
        {
            InitializeComponent();
            FillComboBox();

            var currentRealtorName = Login.UserName;
            TBxRealtor.Text = currentRealtorName;
            _realtorId = Login.UserId;

            /// чтоьы не летело на добавлении в базу ДЛЯ НИХ НУЖНА ВАЛИДАЦИЯ!!
            PlotAreaTBx.Text = "0";
            BusStopTBx.Text = "0";
            ForestTBx.Text = "0";
            LakeTBx.Text = "0";
            RailwayTBx.Text = "0";
            TBxCost.Text = "0";
            ShowTimeTBx.Text = DateTime.Now.ToString();


            _isEdit = false;

        }

        public PlotCard(Guid plotId)
        {
            InitializeComponent();
            _plotId = plotId;

            FillComboBox();
            _isEdit = true;

            var currentPlot = AppController.ImmoRepository.GetPlotsById(plotId);

            var currentRealtorId = currentPlot.FinancialData.FinancialDataRealtorId;
            User realtor = AppController.ImmoRepository.GetUserById(currentRealtorId);
            TBxRealtor.Text = realtor.UserFirstName + " " + realtor.UserLastName.Substring(0, 1) + ". " + realtor.UserThirdName.Substring(0, 1)+ ".";
            _realtorId = realtor.UserId;

            FillPlotsForm(currentPlot);
            _plotNewGuid = AddPlot(false); //автодобавление - false

        }

        public class RegionsComboBox
        {
            public string RegionName { get; set; }
            public Guid RegionGuid { get; set; }

            public RegionsComboBox(string regionName,
                                 Guid regionGuid)
            {
                RegionName = regionName;
                RegionGuid = regionGuid;
            }
        }

        public class SellsTermsComboBox
        {
            public string SellsTermsName { get; set; }
            public Guid SellsTermsGuid { get; set; }

            public SellsTermsComboBox(string regionName,
                                 Guid regionGuid)
            {
                SellsTermsName = regionName;
                SellsTermsGuid = regionGuid;
            }
        }

        private void FillComboBox()
        {
            var regionsComboBoxCollection = new List<RegionsComboBox>();
            regionsComboBoxCollection.AddRange(AppController.ImmoRepository.GetAllRegions().Select(region =>
                                                                                                   new RegionsComboBox(
                                                                                                       region.RegionName,
                                                                                                       region.RegionId)));

            var sellsTermsComboBoxCollection = new List<SellsTermsComboBox>();
            sellsTermsComboBoxCollection.AddRange(
                AppController.ImmoRepository.GetAllSellTerms().Select(
                    term => new SellsTermsComboBox(term.SellTermsName, term.SellTermsId)));

            PlotRegionComboBx.ItemsSource = regionsComboBoxCollection;
            PlotSellsTermsBx.ItemsSource = sellsTermsComboBoxCollection;

            PlotSellsTermsBx.SelectedItem = sellsTermsComboBoxCollection[0];
            PlotRegionComboBx.SelectedItem = regionsComboBoxCollection[0];
        }

        private void FillPlotsForm(Plots currentPlot)
        {
            User realtor = currentPlot.FinancialData.User;

            FIOOwnerBx.Text = currentPlot.Owner.OwnerName;
            PhoneOwnerBx.Text = currentPlot.Owner.OwnerMobilePhone;
            PhoneOwnerAddBx.Text = currentPlot.Owner.OwnerHomePhone;
            objectTBx.Text = currentPlot.PlotsObject;
            PlotAddressTBx.Text = currentPlot.PlotsAddress;
            PlotNearestSignsTBx.Text = currentPlot.PlotsNearestSign;
            PlotAreaTBx.Text = currentPlot.PlotsArea.ToString();
            BuildingRightTBx.Text = currentPlot.PlotsBuildingRights;

            MasteredChBx.IsChecked = currentPlot.PlotsMastered;
            RegistrationChBx.IsChecked = currentPlot.PlotsRegistration;

            checkBox1.IsChecked = currentPlot.PlotsCommunicationWater;
            checkBox2.IsChecked = currentPlot.PlotsCommunicationSewage;
            checkBox3.IsChecked = currentPlot.PlotsCommunicationElectricPower;
            checkBox4.IsChecked = currentPlot.PlotsCommunicationGasSupply;

            FillDistance(BusStopTBx, ChkBusStop, (double) currentPlot.PlotsDistanceFromBusStop);
            FillDistance(ForestTBx, ChkForest, (double)currentPlot.PlotsDistanceFromForest);
            FillDistance(RailwayTBx, ChkRailway, (double)currentPlot.PlotsDistanceFromRailwayStation);
            FillDistance(LakeTBx, ChkLake, (double)currentPlot.PlotsDistanceFromLake);
            
            //ForestTBx.Text = currentPlot.PlotsDistanceFromForest.ToString();
            //LakeTBx.Text = currentPlot.PlotsDistanceFromLake.ToString();
            //RailwayTBx.Text = currentPlot.PlotsDistanceFromRailwayStation.ToString();
            
            ShowTimeTBx.Text = currentPlot.PlotsShowDate.ToString();
            ShowTermsTBx.Text = currentPlot.PlotsShowTerms;
            DocumentsReadyTBx.Text = currentPlot.PlotsDocumentsReady;
            TargetTBx.Text = currentPlot.PlotsPurpose;
            AdditionalIfrormationTBx.Text = currentPlot.PlotsAdditionalInformation;
            PlotHowToGetByTransportTBx.Text = currentPlot.PlotsHowToGetByTransport;
            TBxCardNumber.Text = currentPlot.FinancialData.FinancialDataCardNumber.ToString();
            FinDateDate.SelectedDate = currentPlot.FinancialData.FinancialDataDate;
            TBxRealtor.Text = realtor.UserFirstName + " " + realtor.UserLastName + ". " + realtor.UserThirdName + ".";
            TBxContractNumber.Text = currentPlot.FinancialData.FnancialDataContract;
            TBxSource.Text = currentPlot.FinancialData.FinancialDataSource;
            TBxCost.Text = currentPlot.FinancialData.FinancialDataPrice.ToString();

            PlotRegionComboBx.SelectedValue = currentPlot.PlotsRegionId;
            PlotSellsTermsBx.SelectedValue = currentPlot.PlotsSellTermsId;



        }


        private void FillDistance(DoubleUpDown tbx, CheckBox cbx, double value)
        {
            if (value == 0)
            {
                tbx.Text = "0";
                cbx.IsChecked = false;
                tbx.Visibility = System.Windows.Visibility.Hidden;
            }
            else
            {
                tbx.Text = value.ToString();
                cbx.IsChecked = true;
                tbx.Visibility = System.Windows.Visibility.Visible;
            }
        }

        private Guid AddPlot(bool isShown)
        {
            if(FinDateDate.SelectedDate == null)
            {
                FinDateDate.SelectedDate = DateTime.Today;
            }
            Guid financialDataId = AppController.ImmoRepository.AddFinancialData(FinDateDate.SelectedDate,
                                                                                 double.Parse(TBxCost.Text), double.Parse(TBxCost.Text),
                                                                                 _realtorId, TBxContractNumber.Text, TBxSource.Text);

            _numberCard = AppController.ImmoRepository.GetFinancialDataById(financialDataId).FinancialDataCardNumber.ToString();

            Guid ownerId = AppController.ImmoRepository.AddOwner(PhoneOwnerBx.Text, PhoneOwnerAddBx.Text,
                                                                 FIOOwnerBx.Text);

            var plotId = AppController.ImmoRepository.AddPlot(AdditionalIfrormationTBx.Text, PlotAddressTBx.Text, double.Parse(PlotAreaTBx.Text),BuildingRightTBx.Text,
                checkBox3.IsChecked, checkBox4.IsChecked, checkBox2.IsChecked, checkBox1.IsChecked, double.Parse(BusStopTBx.Text), double.Parse(ForestTBx.Text),
                double.Parse(LakeTBx.Text), double.Parse(RailwayTBx.Text), financialDataId, DocumentsReadyTBx.Text, PlotNearestSignsTBx.Text,objectTBx.Text,
                ownerId, Guid.Parse(PlotRegionComboBx.SelectedValue.ToString()), RegistrationChBx.IsChecked, TargetTBx.Text, MasteredChBx.IsChecked,
                DateTime.Parse(ShowTimeTBx.Text),Guid.Parse(PlotSellsTermsBx.SelectedValue.ToString()), PlotHowToGetByTransportTBx.Text, ShowTermsTBx.Text, 
                isShown);

            if(isShown)
                AddChangingStory("Добавление карточки земельного участка", "", "", "add");
            return plotId;
        }


        private void EditPlot()
        {
            AddChangingStory("Начало редактирования карточки земельного участка", "", "", "edit");
            var plot = AppController.ImmoRepository.GetPlotsById(_plotId);
            _numberCard = plot.FinancialData.FinancialDataCardNumber.ToString();

            #region ADD HISTORY
            DateTime financialDate = (DateTime) plot.FinancialData.FinancialDataDate;
            if (financialDate != FinDateDate.SelectedDate)
            {
                financialDate = (DateTime) FinDateDate.SelectedDate;
                AddChangingStory("Изменение поля <Число>", financialDate.ToString(),
                                 plot.FinancialData.FinancialDataDate.ToString(), "edit field");
            }
            double financialDataPrice = (double) plot.FinancialData.FinancialDataPrice;
            if (financialDataPrice != double.Parse(TBxCost.Text))
            {
                financialDataPrice = double.Parse(TBxCost.Text);
                AddChangingStory("Изменение поля <Цена>", financialDataPrice.ToString(),
                                 plot.FinancialData.FinancialDataPrice.ToString(), "edit field");
            }


            string contractNumber = plot.FinancialData.FnancialDataContract;
            if (contractNumber != TBxContractNumber.Text)
            {
                contractNumber = TBxContractNumber.Text;
                AddChangingStory("Изменение поля <Договор>", contractNumber,
                                 plot.FinancialData.FnancialDataContract, "edit field");
            }
            string addInfo = plot.PlotsAdditionalInformation;
            if (addInfo != AdditionalIfrormationTBx.Text)
            {
                addInfo = AdditionalIfrormationTBx.Text;
                AddChangingStory("Изменение поля <Дополнительные сведения>", addInfo,
                                 plot.PlotsAdditionalInformation, "edit field");
            }
            string address = plot.PlotsAddress;
            if (address != PlotAddressTBx.Text)
            {
                address = PlotAddressTBx.Text;
                AddChangingStory("Изменение поля <Адрес>", address,
                                 plot.PlotsAddress, "edit field");
            }
            double area = (double) plot.PlotsArea;
            if (area != double.Parse(PlotAreaTBx.Text))
            {
                area = double.Parse(PlotAreaTBx.Text);
                AddChangingStory("Изменение поля <Площадь>", area.ToString(),
                                 plot.PlotsArea.ToString(), "edit field");
            }
            string buildingRights = plot.PlotsBuildingRights;
            if (buildingRights != BuildingRightTBx.Text)
            {
                buildingRights = BuildingRightTBx.Text;
                AddChangingStory("Изменение поля <Право на строительство>", buildingRights,
                                 plot.PlotsBuildingRights, "edit field");
            }
            bool isElectricPower = (bool) plot.PlotsCommunicationElectricPower;
            if (isElectricPower != checkBox3.IsChecked)
            {
                isElectricPower = (bool) checkBox3.IsChecked;
                AddChangingStory("Изменение поля <Наличие электроэнергии>", isElectricPower.ToString(),
                                 plot.PlotsCommunicationElectricPower.ToString(), "edit field");
            }
            bool isGas = (bool) plot.PlotsCommunicationGasSupply;
            if (isGas != checkBox4.IsChecked)
            {
                isGas = (bool) checkBox4.IsChecked;
                AddChangingStory("Изменение поля <Наличие газоснабжения>", isGas.ToString(),
                                 plot.PlotsCommunicationGasSupply.ToString(), "edit field");
            }
            bool isSewage = (bool) plot.PlotsCommunicationSewage;
            if (isSewage != checkBox2.IsChecked)
            {
                isSewage = (bool) checkBox2.IsChecked;
                AddChangingStory("Изменение поля <Наличие канализации>", isSewage.ToString(),
                                 plot.PlotsCommunicationSewage.ToString(), "edit field");
            }
            bool isWater = (bool) plot.PlotsCommunicationWater;
            if (isWater != checkBox1.IsChecked)
            {
                isWater = (bool) checkBox1.IsChecked;
                AddChangingStory("Изменение поля <Наличие водоснабжения>", isWater.ToString(),
                                 plot.PlotsCommunicationWater.ToString(), "edit field");
            }
            double distanceBus = (double) plot.PlotsDistanceFromBusStop;
            if (distanceBus != double.Parse(BusStopTBx.Text))
            {
                distanceBus = double.Parse(BusStopTBx.Text);
                AddChangingStory("Изменение поля <Рассстояние до автобусной остановки>", distanceBus.ToString(),
                                 plot.PlotsDistanceFromBusStop.ToString(), "edit field");
            }
            double distanceForest = (double) plot.PlotsDistanceFromForest;
            if (distanceForest != double.Parse(ForestTBx.Text))
            {
                distanceForest = double.Parse(ForestTBx.Text);
                AddChangingStory("Изменение поля <Рассстояние до леса>", distanceForest.ToString(),
                                 plot.PlotsDistanceFromForest.ToString(), "edit field");
            }
            double distanceLake = (double) plot.PlotsDistanceFromLake;
            if (distanceLake != double.Parse(LakeTBx.Text))
            {
                distanceLake = double.Parse(LakeTBx.Text);
                AddChangingStory("Изменение поля <Рассстояние до озера>", distanceLake.ToString(),
                                 plot.PlotsDistanceFromLake.ToString(), "edit field");
            }
            double distanceStation = (double) plot.PlotsDistanceFromRailwayStation;
            if (distanceStation != double.Parse(RailwayTBx.Text))
            {
                distanceStation = double.Parse(RailwayTBx.Text);
                AddChangingStory("Изменение поля <Рассстояние до станции>", distanceStation.ToString(),
                                 plot.PlotsDistanceFromRailwayStation.ToString(), "edit field");
            }
            string documentsReady = plot.PlotsDocumentsReady;
            if (documentsReady != DocumentsReadyTBx.Text)
            {
                documentsReady = DocumentsReadyTBx.Text;
                AddChangingStory("Изменение поля <Готовность документов к продаже>", documentsReady,
                                 plot.PlotsDocumentsReady, "edit field");
            }
            string nearestSign = plot.PlotsNearestSign;
            if (nearestSign != PlotNearestSignsTBx.Text)
            {
                nearestSign = PlotNearestSignsTBx.Text;
                AddChangingStory("Изменение поля <Ближайшие ориентиры>", nearestSign,
                                 plot.PlotsNearestSign, "edit field");
            }
            string objectName = plot.PlotsObject;
            if (objectName != objectTBx.Text)
            {
                objectName = objectTBx.Text;
                AddChangingStory("Изменение поля <Наименование объекта>", objectName,
                                 plot.PlotsObject, "edit field");
            }
            string homePhone = plot.Owner.OwnerHomePhone;
            if (homePhone != PhoneOwnerAddBx.Text)
            {
                homePhone = PhoneOwnerAddBx.Text;
                AddChangingStory("Изменение поля <Дополнительный телефон сщбственника>", homePhone,
                                 plot.Owner.OwnerHomePhone, "edit field");
            }
            string mobilePhone = plot.Owner.OwnerMobilePhone;
            if (mobilePhone != PhoneOwnerBx.Text)
            {
                mobilePhone = PhoneOwnerBx.Text;
                AddChangingStory("Изменение поля <Телефон собственника>", mobilePhone,
                                 plot.Owner.OwnerMobilePhone, "edit field");
            }
            string fio = plot.Owner.OwnerName;
            if (fio != FIOOwnerBx.Text)
            {
                fio = FIOOwnerBx.Text;
                AddChangingStory("Изменение поля <ФИО собственника>", fio,
                                 plot.Owner.OwnerName, "edit field");
            }
            var region = plot.PlotsRegionId;
            if (region != Guid.Parse(PlotRegionComboBx.SelectedValue.ToString()))
            {
                region = (Guid) PlotRegionComboBx.SelectedValue;
                AddChangingStory("Изменение поля <Район>",
                                 PlotRegionComboBx.Text,
                                 plot.Region.RegionName, "edit field");
            }
            bool isRegistration = (bool) plot.PlotsRegistration;
            if (isRegistration != RegistrationChBx.IsChecked)
            {
                isRegistration = (bool) RegistrationChBx.IsChecked;
                AddChangingStory("Изменение поля <Прописка>", isRegistration.ToString(),
                                 plot.PlotsRegistration.ToString(), "edit field");
            }
            string purpose = plot.PlotsPurpose;
            if (purpose != TargetTBx.Text)
            {
                purpose = TargetTBx.Text;
                AddChangingStory("Изменение поля <Целевое назначение>", purpose,
                                 plot.PlotsPurpose, "edit field");
            }
            bool isMaster = (bool) plot.PlotsMastered;
            if (isMaster != MasteredChBx.IsChecked)
            {
                isMaster = (bool) MasteredChBx.IsChecked;
                AddChangingStory("Изменение поля <Прописка>", isMaster.ToString(),
                                 plot.PlotsMastered.ToString(), "edit field");
            }

            DateTime showDate = (DateTime) plot.PlotsShowDate;
            if (showDate != DateTime.Parse(ShowTimeTBx.Text))
            {
                showDate = DateTime.Parse(ShowTimeTBx.Text);
                AddChangingStory("Изменение поля <Время показа>", showDate.ToString(),
                                 plot.PlotsShowDate.ToString(), "edit field");
            }
            var cellTerms = plot.PlotsSellTermsId;
            if (cellTerms != Guid.Parse(PlotSellsTermsBx.SelectedValue.ToString()))
            {
                cellTerms = (Guid) PlotSellsTermsBx.SelectedValue;
                AddChangingStory("Изменение поля <Условия продажи>",
                                 PlotSellsTermsBx.Text,
                                 plot.SellTerms.SellTermsName, "edit field");
            }
            string howToGetByTransport = plot.PlotsHowToGetByTransport;
            if (howToGetByTransport != PlotHowToGetByTransportTBx.Text)
            {
                howToGetByTransport = PlotHowToGetByTransportTBx.Text;
                AddChangingStory("Изменение поля <Как добраться общественным транспортом>", howToGetByTransport,
                                 plot.PlotsHowToGetByTransport, "edit field");
            }
            string showTerms = plot.PlotsShowTerms;
            if (showTerms != ShowTermsTBx.Text)
            {
                showTerms = ShowTermsTBx.Text;
                AddChangingStory("Изменение поля <Как добраться общественным транспортом>", showTerms,
                                 plot.PlotsShowTerms, "edit field");
            }
            string finSource = plot.FinancialData.FinancialDataSource;
            if (finSource != TBxSource.Text)
            {
                finSource = TBxSource.Text;
                AddChangingStory("Изменение поля <Источник>", finSource,
                                 plot.FinancialData.FinancialDataSource, "edit field");
            }

            #endregion ADD HISTORY

            AppController.ImmoRepository.EditFinancialData(plot.PlotsFinancialDataId, financialDate, financialDataPrice,
                                                           financialDataPrice, _realtorId, contractNumber, finSource);
            AppController.ImmoRepository.EditOwner(plot.PlotsOwnerId, homePhone, mobilePhone, fio);
            AppController.ImmoRepository.EditPlots(_plotId, addInfo, address, area, buildingRights, isElectricPower,
                                                   isGas, isSewage, isWater, distanceBus, distanceForest,
                                                   distanceLake, distanceStation, plot.PlotsFinancialDataId,
                                                   documentsReady, nearestSign, objectName, plot.PlotsOwnerId, region,
                                                   isRegistration, purpose,
                                                   isMaster, showDate, cellTerms, howToGetByTransport, showTerms, 
                                                   _plotNewGuid);


            AddChangingStory("Окончание редактирования карточки земельного участка", "", "", "edit");
        }

        private void AddChangingStory(string operation, string newValue, string oldValue, string state)
        {
            AppController.ImmoRepository.AddChangingStory(operation, _plotId, newValue, oldValue, _realtorId, state,
                                                          _numberCard);
        }

        private void BTnOk_Click(object sender, RoutedEventArgs e)
        {
            if (ValidateAll())
            {
                //throw new NotImplementedException();
                if (!_isEdit)
                    AddPlot(true); //true - потому что добавляем новый участок (не автодобавление)
                else
                    EditPlot();
                Close();
            }
            else
            {
                MessageBox.Show("Одно или несколько полей заполнены некорректно!","Ошибка");
            }
        }

        private void BTnCancel_Click(object sender, RoutedEventArgs e)
        {
            AppController.ImmoRepository.DeletePlots(_plotNewGuid);
            Close();
        }

        private void ChkBusStop_Checked(object sender, RoutedEventArgs e)
        {
            if ((bool)ChkBusStop.IsChecked)
            {
                BusStopTBx.Visibility = Visibility.Visible;
            }
            else
            {
                BusStopTBx.Visibility = Visibility.Hidden;
                BusStopTBx.Text = "0";
            }
        }

        private void ChkForest_Checked(object sender, RoutedEventArgs e)
        {
            if ((bool)ChkForest.IsChecked)
            {
                ForestTBx.Visibility = Visibility.Visible;
            }
            else
            {
                ForestTBx.Visibility = Visibility.Hidden;
                ForestTBx.Text = "0";
            }

        }

        private void ChkLake_Checked(object sender, RoutedEventArgs e)
        {
            if ((bool)ChkLake.IsChecked)
            {
                LakeTBx.Visibility = Visibility.Visible;
            }
            else
            {
                LakeTBx.Visibility = Visibility.Hidden;
                LakeTBx.Text = "0";
            }
        }

        private void ChkRailway_Checked(object sender, RoutedEventArgs e)
        {
            if ((bool)ChkRailway.IsChecked)
            {
                RailwayTBx.Visibility = Visibility.Visible;
            }
            else
            {
                RailwayTBx.Visibility = Visibility.Hidden;
                RailwayTBx.Text = "0";
            }
        }

        private void ShowMapBtn_Click(object sender, RoutedEventArgs e)
        {
            var map = new Map();
            if (map.Find(((ComboBoxItem)PlotRegionComboBx.SelectedItem).Content + " " + PlotAddressTBx.Text))
                map.ShowDialog();
            else Microsoft.Windows.Controls.MessageBox.Show("Не удалось определить местоположение!", "Ошибка определения местоположения");
        }

        private void BtnAccept_Click(object sender, RoutedEventArgs e)
        {
            AppController.ImmoRepository.AcceptPlot(_plotId, true);
            var addedPlot = AppController.ImmoRepository.GetPlotsById(_plotId);

            if ((addedPlot.PlotNewId) == null
                & ((bool)addedPlot.PlotsIsShown)) //Была добавлена
            {
                //Все уже сделано! Для различия добавленно записи и редактируемой хватает только хвостового guid, а для различия
                //с хвостовой записью нужен еще флаг IsShown
            }
            else
            {
                AppController.ImmoRepository.DeletePlots(addedPlot.PlotNewId); //Удаляем главную запись
                AppController.ImmoRepository.BreakPlotNewId(addedPlot.PlotsId);
                AppController.ImmoRepository.SetShownPlot(addedPlot.PlotsId, true); //Делаем дочернюю запись главной
            }
            AppController.ImmoRepository.DeletePlots(_plotNewGuid);

            Close();
        }

        private void BtnReject_Click(object sender, RoutedEventArgs e)
        {
            AppController.ImmoRepository.AcceptPlot(_plotId, false);
            var addedPlot = AppController.ImmoRepository.GetPlotsById(_plotId);

            if (addedPlot.PlotNewId == null) //Была добавлена
            {
                AppController.ImmoRepository.DeletePlots(_plotId);
            }
            else
            {
                AppController.ImmoRepository.DeletePlots(addedPlot.PlotsId);
                AppController.ImmoRepository.BreakPlotNewId(addedPlot.PlotNewId);
                AppController.ImmoRepository.SetShownPlot(addedPlot.PlotNewId, true);
            }

            AppController.ImmoRepository.DeletePlots(_plotNewGuid);
            Close();
        }



        private void PlotAreaTBx_KeyDown(object sender, KeyEventArgs e)
        {
            
        }

        private bool ValidateAll()
        {
            return (PlotAreaTBx.Value != null 
                & PlotAreaTBx.Text != string.Empty
                & FinDateDate.SelectedDate != null);
        }

        private void PlotAreaTBx_ValueChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (PlotAreaTBx.Value == null || PlotAreaTBx.Text == "")
            {
                AreaValidationBorder.BorderBrush = Brushes.Red;
                AreaValidationBorder.BorderThickness = new Thickness(1);
            }
            else
            {
                AreaValidationBorder.BorderBrush = Brushes.Green;
                AreaValidationBorder.BorderThickness = new Thickness(0);
            }
        }

        private void FinDateDate_DateValidationError(object sender, DatePickerDateValidationErrorEventArgs e)
        {
            FinDateBorder.BorderBrush = Brushes.Red;
            FinDateBorder.BorderThickness = new Thickness(1);
        }

        private void FinDateDate_LostFocus(object sender, RoutedEventArgs e)
        {

        }
    }
}
